package com.module.ble.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.DashPathEffect
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Shader
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.common.app.R
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.dp2px
import com.module.ble.data.bean.CusChartData
import java.util.Calendar
import kotlin.math.abs

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：9/7/2025
 *
 * 描述：压力折线图表
 * X轴：24小时（00:00-24:00），每30分钟一个数据点，共48个点
 * Y轴：压力值范围0-100
 * 修订历史：
 *
 */
class StressBrokenLineChart @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 触摸回调接口
    interface OnStressPointTouchListener {
        /**
         * 触摸到数据点时的回调
         * @param pointIndex 数据点索引（0-47）
         * @param value 压力值（0-100）
         * @param timeLabel 时间标签（如："00:00", "00:30"等）
         */
        fun onPointTouch(pointIndex: Int, value: Float, timeLabel: String)
    }

    // 数据相关
    private var dataValues = mutableListOf<CusChartData>()
    private var touchListener: OnStressPointTouchListener? = null
    private var benchmarkingDataValues = mutableListOf<CusChartData>()

    // 绘制相关的Paint对象
    private lateinit var blackLinePaint: Paint // 黑色指示实线画笔
    private lateinit var coordinatePoint: Paint // 坐标点
    private lateinit var paintSolidLine: Paint // 实线画笔
    private lateinit var paintPolyShadow: Paint // 折线阴影
    private lateinit var paintRound: Paint // 指示滑块圆
    private lateinit var paintSolidBenchmarkingLine: Paint // 对标实线画笔

    // 颜色配置
    private var paintPolylineDefaultColor = getColor(R.color.c_5282ff) // 压力折线颜色
    private val backgroundShadowColor = getColor(R.color.c_bcceff)// 折线阴影颜色
    private var realTimeIndicatorColor = getColor(R.color.color_d9d9d9) // 实时指示器竖线颜色
    private var realTimeCircleColor = getColor(R.color.color_d9d9d9) // 实时指示器圆点颜色
    private var paintTempPolylineDefaultColor = getColor(R.color.c_ff8a7f) // 临时折线颜色

    // 选中数据圆点大小
    private val blueCircleRadius = dp2px(3f)

    // 触摸相关
    private var isTouching = false
    private var touchedPointIndex = -1
    private var xSlider = 0f
    private var circleY = 0f

    // 阴影绘制控制开关
    private var isShadowEnabled = false
    // 触摸控制开关
    private var isTouchEnabled = false
    // 线条样式控制开关
    private var isDashedLineEnabled = false

    // 实时指示器控制开关
    private var isRealTimeIndicatorEnabled = true
    // 实时指示器相关属性
    private var currentTimePointIndex = -1
    private var realTimeIndicatorX = 0f
    private var realTimeIndicatorY = 0f
    // 实时指示器画笔
    private lateinit var realTimeIndicatorPaint: Paint
    private lateinit var realTimeCirclePaint: Paint

    // 柱状背景功能
    private var selectType = -1 // -1表示不显示，0-3分别对应不同区间
    // Y轴色块颜色配置
    private val yAxisStageColors = arrayOf(
        ViewUtils.getColor(R.color.c_bcceff), // 0-30: 浅蓝色
        ViewUtils.getColor(R.color.c_86b1ff), // 30-60: 天蓝色
        ViewUtils.getColor(R.color.c_5282ff), // 60-80: 深蓝色
        ViewUtils.getColor(R.color.c_ff8a06) // 80-100: 橙色
    )
    private lateinit var columnBackgroundPaint: Paint

    // 时间标签（48个点，每30分钟一个）
    private val timeLabels = generateTimeLabels()

    private var beforePointIndex =  0

    init {
        // 获取自定义属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.StressBrokenLineChart)
        paintPolylineDefaultColor = typedArray.getColor(R.styleable.StressBrokenLineChart_stress_bl_lineDefaultColor, paintPolylineDefaultColor)
        realTimeIndicatorColor = typedArray.getColor(R.styleable.StressBrokenLineChart_stress_bl_realTimeIndicatorColor, realTimeIndicatorColor)
        realTimeCircleColor = typedArray.getColor(R.styleable.StressBrokenLineChart_stress_bl_realTimeCircleColor, realTimeCircleColor)
        isDashedLineEnabled = typedArray.getBoolean(R.styleable.StressBrokenLineChart_stress_bl_showDashedLine, isDashedLineEnabled)
        typedArray.recycle()

        initPaint()
    }

    private fun initPaint() {

        blackLinePaint = Paint().apply {
            style = Paint.Style.STROKE
            strokeWidth = dp2px(2f)
            color =getColor(R.color.text_content)
            isAntiAlias = true
        }
        paintPolyShadow = Paint().apply {
            style = Paint.Style.FILL
            isAntiAlias = true
        }

        // 实线画笔（用于正常数据连接）
        paintSolidLine = Paint().apply {
            style = Paint.Style.STROKE
            strokeWidth = dp2px(1.5f)
            color = paintPolylineDefaultColor
            isAntiAlias = true
        }

        paintSolidBenchmarkingLine = Paint().apply {
            style = Paint.Style.STROKE
            strokeWidth = dp2px(1.5f)
            color = paintTempPolylineDefaultColor
            isAntiAlias = true
        }

        paintRound = Paint().apply {
            style = Paint.Style.FILL
            isAntiAlias = true
            color = paintPolylineDefaultColor
        }

        coordinatePoint = Paint().apply {
            style = Paint.Style.FILL
            isAntiAlias = true
            color = paintPolylineDefaultColor
        }

        // 实时指示器画笔
        realTimeIndicatorPaint = Paint().apply {
            style = Paint.Style.STROKE
            strokeWidth = dp2px(1f)
            color = realTimeIndicatorColor
            isAntiAlias = true
        }

        realTimeCirclePaint = Paint().apply {
            style = Paint.Style.FILL
            isAntiAlias = true
            color = realTimeCircleColor
        }

        // 柱状背景画笔
        columnBackgroundPaint = Paint().apply {
            style = Paint.Style.FILL
            color = getColor(R.color.c_f0f0f0) // 默认浅灰色背景
            alpha = 128 // 半透明效果
            isAntiAlias = true
        }

        // 根据开关设置线条样式
        updateLineStyle()
    }

    private fun generateTimeLabels(): List<String> {
        val labels = mutableListOf<String>()
        for (hour in 0..23) {
            labels.add(String.format("%02d:00", hour))
            if (hour < 23) {
                labels.add(String.format("%02d:30", hour))
            }
        }
        labels.add("24:00") // 添加最后一个点
        return labels
    }

    private fun getColor(resId: Int): Int {
        return context.getColor(resId)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        val desiredWidth = dp2px(350f).toInt()
        val desiredHeight = dp2px(200f).toInt()

        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)

        val width = when (widthMode) {
            MeasureSpec.EXACTLY -> widthSize
            MeasureSpec.AT_MOST -> minOf(desiredWidth, widthSize)
            else -> desiredWidth
        }

        val height = when (heightMode) {
            MeasureSpec.EXACTLY -> heightSize
            MeasureSpec.AT_MOST -> minOf(desiredHeight, heightSize)
            else -> desiredHeight
        }

        setMeasuredDimension(width, height)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        // 当视图大小改变时，更新实时指示器位置
        if (isRealTimeIndicatorEnabled && dataValues.isNotEmpty()) {
            updateRealTimeIndicator()
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val chartHeight = height.toFloat()

        // 绘制柱状背景（在折线之前绘制）
        if (selectType in 0..3) {
            drawColumnBackground(canvas, chartHeight)
        }

        // 绘制折线和阴影
        drawStressLine(canvas, chartHeight)

        // 绘制对标折线和阴影
        drawBenchmarkingStressLine(canvas, chartHeight)

        // 绘制触摸指示器
        if (isTouching && touchedPointIndex >= 0) {
            drawTouchIndicator(canvas, chartHeight)
        }

        // 绘制实时指示器
        if (isRealTimeIndicatorEnabled && currentTimePointIndex >= 0) {
            drawRealTimeIndicator(canvas, chartHeight)
        }
    }

    /**
     * 判断数据点是否在选定的区间内
     */
    private fun isValueInSelectedRange(value: Float): Boolean {
        return when (selectType) {
            0 -> value in 0f..30f
            1 -> value in 31f..60f
            2 -> value in 61f..80f
            3 -> value in 81f..100f
            else -> false
        }
    }

    /**
     * 计算柱状背景的宽度
     */
    private fun calculateColumnWidth(index: Int, xStep: Float): Float {
        val leftHalf = if (index > 0) xStep / 2f else 0f
        val rightHalf = if (index < dataValues.size - 1) xStep / 2f else 0f
        return leftHalf + rightHalf
    }

    /**
     * 绘制柱状背景
     */
    private fun drawColumnBackground(canvas: Canvas, chartHeight: Float) {
        if (dataValues.isEmpty()) return

        val lineEndX = width.toFloat()
        val xWithStart = 0f
        val xWithEnd = lineEndX
        val xStep = (xWithEnd - xWithStart) / (dataValues.size - 1)

        for (i in dataValues.indices) {
            val data = dataValues[i]
            if (isValueInSelectedRange(data.mValue)) {
                val centerX = xWithStart + i * xStep
                val columnWidth = calculateColumnWidth(i, xStep)
                val leftX = centerX - columnWidth / 2f
                val rightX = centerX + columnWidth / 2f

                // 根据当前折点的值设置背景颜色
                val backgroundColor = getBackgroundColorByValue(data.mValue)
                columnBackgroundPaint.color = backgroundColor
                columnBackgroundPaint.alpha = 128 // 保持半透明效果

                // 绘制从顶部到底部的柱状背景
                canvas.drawRect(leftX, 0f, rightX, chartHeight, columnBackgroundPaint)
            }
        }
    }

    private fun drawStressLine(canvas: Canvas, chartHeight: Float) {
        if (dataValues.isEmpty()) return

        val lineEndX = width.toFloat()
        val xWithStart = 0f
        val xWithEnd = lineEndX
        val xStep = (xWithEnd - xWithStart) / (dataValues.size - 1)

        // 绘制阴影区域（仅当开关开启时）
        val shadowPath = Path()
        var shadowStarted = false

        // 第一步：绘制连线（只连接相邻的有效数据点）
        for (i in 0 until dataValues.size - 1) {
            val currentData = dataValues[i]
            val nextData = dataValues[i + 1]

            // 只有当两个相邻数据点都是有效值时才绘制连线
            if (currentData.mValue >= 0 && nextData.mValue >= 0) {
                val x0 = xWithStart + i * xStep
                val y0 = chartHeight - (currentData.mValue / 100f) * chartHeight
                val x1 = xWithStart + (i + 1) * xStep
                val y1 = chartHeight - (nextData.mValue / 100f) * chartHeight

                // 绘制连线
                canvas.drawLine(x0, y0, x1, y1, paintSolidLine)

                // 处理阴影路径
                if (isShadowEnabled && currentData.mValue > 0 && nextData.mValue > 0) {
                    if (!shadowStarted) {
                        shadowPath.moveTo(x0, chartHeight)
                        shadowPath.lineTo(x0, y0)
                        shadowStarted = true
                    }
                    shadowPath.lineTo(x1, y1)
                } else if (isShadowEnabled && shadowStarted && (nextData.mValue == 0f || i == dataValues.size - 2)) {
                    // 结束当前阴影段
                    shadowPath.lineTo(x1, chartHeight)
                    shadowPath.close()
                    shadowStarted = false
                }
            } else if (isShadowEnabled && shadowStarted) {
                // 如果遇到-1值，结束当前阴影段
                val x0 = xWithStart + i * xStep
                shadowPath.lineTo(x0, chartHeight)
                shadowPath.close()
                shadowStarted = false
            }
        }

        // 第二步：绘制孤立的有效数据点（用短折线段表示）
        for (i in dataValues.indices) {
            val data = dataValues[i]
            if (data.mValue >= 0) {
                val hasLeftConnection = i > 0 && dataValues[i - 1].mValue >= 0
                val hasRightConnection = i < dataValues.size - 1 && dataValues[i + 1].mValue >= 0

                // 如果是孤立点（左右都没有连接），绘制短折线段
                if (!hasLeftConnection && !hasRightConnection) {
                    val x = xWithStart + i * xStep
                    val y = chartHeight - (data.mValue / 100f) * chartHeight

                    // 计算短线段的长度（相邻数据点间距的一半）
                    val halfStep = xStep / 2f
                    val leftX = x - halfStep
                    val rightX = x + halfStep

                    // 绘制水平短线段
                    canvas.drawLine(leftX, y, rightX, y, paintSolidLine)

                    // 绘制孤立点的阴影（仅当开关开启且值大于0时）
                    if (isShadowEnabled && data.mValue > 0) {
                        val isolatedShadowPath = Path()
                        isolatedShadowPath.moveTo(leftX, chartHeight)
                        isolatedShadowPath.lineTo(leftX, y)
                        isolatedShadowPath.lineTo(rightX, y)
                        isolatedShadowPath.lineTo(rightX, chartHeight)
                        isolatedShadowPath.close()

                        val shadowShader = LinearGradient(
                            0f, 0f,
                            0f, chartHeight,
                            backgroundShadowColor,
                            0x00000000,
                            Shader.TileMode.CLAMP
                        )
                        paintPolyShadow.shader = shadowShader
                        canvas.drawPath(isolatedShadowPath, paintPolyShadow)
                    }
                }
            }
        }

        // 完成最后的阴影路径
        if (isShadowEnabled && shadowStarted) {
            val lastIndex = dataValues.size - 1
            val lastData = dataValues[lastIndex]
            if (lastData.mValue >= 0) {
                val lastX = xWithStart + lastIndex * xStep
                shadowPath.lineTo(lastX, chartHeight)
                shadowPath.close()
            }
        }

        // 绘制连续线段的阴影
        if (isShadowEnabled && !shadowPath.isEmpty) {
            val shadowShader = LinearGradient(
                0f, 0f,
                0f, chartHeight,
                backgroundShadowColor,
                0x00000000,
                Shader.TileMode.CLAMP
            )
            paintPolyShadow.shader = shadowShader
            canvas.drawPath(shadowPath, paintPolyShadow)
        }
    }

    private fun drawBenchmarkingStressLine(canvas: Canvas, chartHeight: Float) {
        if (benchmarkingDataValues.isEmpty()) return

        val lineEndX = width.toFloat()
        val xWithStart = 0f
        val xWithEnd = lineEndX
        val xStep = (xWithEnd - xWithStart) / (benchmarkingDataValues.size - 1)

        // 绘制阴影区域（仅当开关开启时）
        val shadowPath = Path()
        var shadowStarted = false

        // 第一步：绘制连线（只连接相邻的有效数据点）
        for (i in 0 until benchmarkingDataValues.size - 1) {
            val currentData = benchmarkingDataValues[i]
            val nextData = benchmarkingDataValues[i + 1]

            // 只有当两个相邻数据点都是有效值时才绘制连线
            if (currentData.mValue >= 0 && nextData.mValue >= 0) {
                val x0 = xWithStart + i * xStep
                val y0 = chartHeight - (currentData.mValue / 100f) * chartHeight
                val x1 = xWithStart + (i + 1) * xStep
                val y1 = chartHeight - (nextData.mValue / 100f) * chartHeight

                // 绘制连线
                canvas.drawLine(x0, y0, x1, y1, paintSolidBenchmarkingLine)

                // 处理阴影路径
                if (isShadowEnabled && currentData.mValue > 0 && nextData.mValue > 0) {
                    if (!shadowStarted) {
                        shadowPath.moveTo(x0, chartHeight)
                        shadowPath.lineTo(x0, y0)
                        shadowStarted = true
                    }
                    shadowPath.lineTo(x1, y1)
                } else if (isShadowEnabled && shadowStarted && (nextData.mValue == 0f || i == benchmarkingDataValues.size - 2)) {
                    // 结束当前阴影段
                    shadowPath.lineTo(x1, chartHeight)
                    shadowPath.close()
                    shadowStarted = false
                }
            } else if (isShadowEnabled && shadowStarted) {
                // 如果遇到-1值，结束当前阴影段
                val x0 = xWithStart + i * xStep
                shadowPath.lineTo(x0, chartHeight)
                shadowPath.close()
                shadowStarted = false
            }
        }

        // 第二步：绘制孤立的有效数据点（用短折线段表示）
        for (i in benchmarkingDataValues.indices) {
            val data = benchmarkingDataValues[i]
            if (data.mValue >= 0) {
                val hasLeftConnection = i > 0 && benchmarkingDataValues[i - 1].mValue >= 0
                val hasRightConnection = i < benchmarkingDataValues.size - 1 && benchmarkingDataValues[i + 1].mValue >= 0

                // 如果是孤立点（左右都没有连接），绘制短折线段
                if (!hasLeftConnection && !hasRightConnection) {
                    val x = xWithStart + i * xStep
                    val y = chartHeight - (data.mValue / 100f) * chartHeight

                    // 计算短线段的长度（相邻数据点间距的一半）
                    val halfStep = xStep / 2f
                    val leftX = x - halfStep
                    val rightX = x + halfStep

                    // 绘制水平短线段
                    canvas.drawLine(leftX, y, rightX, y, paintSolidBenchmarkingLine)

                    // 绘制孤立点的阴影（仅当开关开启且值大于0时）
                    if (isShadowEnabled && data.mValue > 0) {
                        val isolatedShadowPath = Path()
                        isolatedShadowPath.moveTo(leftX, chartHeight)
                        isolatedShadowPath.lineTo(leftX, y)
                        isolatedShadowPath.lineTo(rightX, y)
                        isolatedShadowPath.lineTo(rightX, chartHeight)
                        isolatedShadowPath.close()

                        val shadowShader = LinearGradient(
                            0f, 0f,
                            0f, chartHeight,
                            backgroundShadowColor,
                            0x00000000,
                            Shader.TileMode.CLAMP
                        )
                        paintPolyShadow.shader = shadowShader
                        canvas.drawPath(isolatedShadowPath, paintPolyShadow)
                    }
                }
            }
        }

        // 完成最后的阴影路径
        if (isShadowEnabled && shadowStarted) {
            val lastIndex = benchmarkingDataValues.size - 1
            val lastData = benchmarkingDataValues[lastIndex]
            if (lastData.mValue >= 0) {
                val lastX = xWithStart + lastIndex * xStep
                shadowPath.lineTo(lastX, chartHeight)
                shadowPath.close()
            }
        }

        // 绘制连续线段的阴影（仅当开关开启时）
        if (isShadowEnabled && !shadowPath.isEmpty) {
            val shadowShader = LinearGradient(
                0f, 0f,
                0f, chartHeight,
                backgroundShadowColor,
                0x00000000,
                Shader.TileMode.CLAMP
            )
            paintPolyShadow.shader = shadowShader
            canvas.drawPath(shadowPath, paintPolyShadow)
        }
    }

    private fun drawTouchIndicator(canvas: Canvas, chartHeight: Float) {
        if (touchedPointIndex < 0 || touchedPointIndex >= dataValues.size) return

        val lineEndX = width.toFloat()
        val xWithStart = 0f
        val xWithEnd = lineEndX
        val xStep = (xWithEnd - xWithStart) / (dataValues.size - 1)

        val x = xWithStart + touchedPointIndex * xStep
        val startY = 0f
        val endY = chartHeight

        // 绘制黑色实线指示器
        canvas.drawLine(x, startY, x, endY, blackLinePaint)

        // 绘制触摸点圆圈
        canvas.drawCircle(x, circleY, blueCircleRadius, paintRound)
    }

    /**
     * 查找父布局中的ViewPager2
     */
    private fun findViewPager2(): androidx.viewpager2.widget.ViewPager2? {
        var parent = parent
        while (parent != null) {
            if (parent is androidx.viewpager2.widget.ViewPager2) {
                return parent
            }
            parent = parent.parent
        }
        return null
    }

    /**
     * 检查触摸点是否在图表区域内
     */
    private fun isTouchInChartArea(touchX: Float, touchY: Float): Boolean {
        // 检查Y轴范围（整个图表高度）
        if (touchY < 0 || touchY > height) {
            return false
        }

        // 检查X轴范围（整个图表宽度）
        return touchX >= 0 && touchX <= width
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        // 检查触摸是否被启用
        if (!isTouchEnabled) {
            return super.onTouchEvent(event)
        }
        if (dataValues.isNullOrEmpty()) return true//无数据是直接透传触摸

        val viewPager2 = findViewPager2()

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                if (isTouchInChartArea(event.x, event.y)) {
                    // 直接禁用ViewPager2的用户输入
                    viewPager2?.isUserInputEnabled = false
                    parent?.requestDisallowInterceptTouchEvent(true)

                    val touchX = event.x
                    val touchedIndex = findNearestDataPoint(touchX)

                    if (touchedIndex >= 0 && touchedIndex < dataValues.size) {
                        isTouching = true
                        touchedPointIndex = touchedIndex

                        val lineEndX = width.toFloat()
                        val xWithStart = 0f
                        val xWithEnd = lineEndX
                        val xStep = (xWithEnd - xWithStart) / (dataValues.size - 1)

                        xSlider = xWithStart + touchedPointIndex * xStep
                        val chartHeight = height.toFloat()
                        circleY = chartHeight - (dataValues[touchedPointIndex].mValue / 100f) * chartHeight

                        // 触发回调
                        touchListener?.onPointTouch(
                            touchedPointIndex,
                            dataValues[touchedPointIndex].mValue,
                            timeLabels[touchedPointIndex]
                        )

                        invalidate()
                        return true
                    }
                }
            }
            MotionEvent.ACTION_MOVE -> {
                if (isTouching && touchedPointIndex >= 0) {
                    val touchX = event.x
                    val touchedIndex = findNearestDataPoint(touchX)

                    if (touchedIndex >= 0 && touchedIndex < dataValues.size) {
                        touchedPointIndex = touchedIndex

                        val lineEndX = width.toFloat()
                        val xWithStart = 0f
                        val xWithEnd = lineEndX
                        val xStep = (xWithEnd - xWithStart) / (dataValues.size - 1)

                        xSlider = xWithStart + touchedPointIndex * xStep
                        val chartHeight = height.toFloat()
                        circleY = chartHeight - (dataValues[touchedPointIndex].mValue / 100f) * chartHeight

                        // 触发回调
                        touchListener?.onPointTouch(
                            touchedPointIndex,
                            dataValues[touchedPointIndex].mValue,
                            timeLabels[touchedPointIndex]
                        )

                        invalidate()
                        return true
                    }
                }
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                // 重新启用ViewPager2的用户输入
                viewPager2?.isUserInputEnabled = true
                parent?.requestDisallowInterceptTouchEvent(false)

                isTouching = false
                touchedPointIndex = -1
                invalidate()
                return true
            }
        }
        return super.onTouchEvent(event)
    }

    /**
     * 根据当前时间戳计算对应的数据点索引
     * @return 数据点索引，如果超出范围返回-1
     * - 1. 小时是15，所以 15 * 2 = 30
     * - 2. 分钟是24，小于30，所以不加1
     */
    private fun calculateCurrentTimePointIndex(): Int {
        val calendar = Calendar.getInstance()
        val currentHour = calendar.get(Calendar.HOUR_OF_DAY)
        val currentMinute = calendar.get(Calendar.MINUTE)

        // 计算当前时间对应的30分钟区间索引
        // 每小时有2个数据点（00:00, 00:30），总共48个点
        val currentPointIndex = currentHour * 2 + if (currentMinute >= 30) 1 else 0

        // 获取前30分钟的时间区间索引（即前一个数据点）
        beforePointIndex = if (currentPointIndex == 0) 0 else currentPointIndex - 1

        // 确保索引在有效范围内
        return if (beforePointIndex >= 0 && beforePointIndex < dataValues.size) beforePointIndex else -1
    }

    /**
     * 更新实时指示器位置
     */
    private fun updateRealTimeIndicator() {
        if (!isRealTimeIndicatorEnabled) {
            currentTimePointIndex = -1
            return
        }

        currentTimePointIndex = calculateCurrentTimePointIndex()

        if (currentTimePointIndex >= 0 && currentTimePointIndex < dataValues.size) {
            val lineEndX = width.toFloat()
            val xWithStart = 0f
            val xWithEnd = lineEndX
            val xStep = (xWithEnd - xWithStart) / (dataValues.size - 1)
            val chartHeight = height.toFloat()

            realTimeIndicatorX = xWithStart + currentTimePointIndex * xStep
            realTimeIndicatorY = chartHeight - (dataValues[currentTimePointIndex].mValue / 100f) * chartHeight
        }
    }

    private fun findNearestDataPoint(touchX: Float): Int {
        val lineEndX = width.toFloat()
        val xWithStart = 0f
        val xWithEnd = lineEndX
        val xStep = (xWithEnd - xWithStart) / (dataValues.size - 1)

        var nearestIndex = -1
        var minDistance = Float.MAX_VALUE

        for (i in dataValues.indices) {
            val x = xWithStart + i * xStep
            val distance = abs(touchX - x)
            if (distance < minDistance && distance < dp2px(20f)) { // 20dp的触摸范围
                minDistance = distance
                nearestIndex = i
            }
        }

        return nearestIndex
    }

    /**
     * 绘制实时指示器
     */
    private fun drawRealTimeIndicator(canvas: Canvas, chartHeight: Float) {
        if (currentTimePointIndex < 0 || currentTimePointIndex >= dataValues.size) return

        // 绘制竖直指示线
        canvas.drawLine(realTimeIndicatorX, 0f, realTimeIndicatorX, chartHeight, realTimeIndicatorPaint)

        // 绘制圆圈指示点
        canvas.drawCircle(realTimeIndicatorX, realTimeIndicatorY, dp2px(3f), realTimeCirclePaint)


        // 绘制对标线圆圈指示点
        if ((currentTimePointIndex < benchmarkingDataValues.size) && (benchmarkingDataValues.size > 2)) {
            val benchmarkingData = benchmarkingDataValues[currentTimePointIndex]
            if (benchmarkingData.mValue >= 0) { // 只有当对标数据有效时才绘制
                val benchmarkingY = chartHeight - (benchmarkingData.mValue / 100f) * chartHeight
                // 使用与对标线相同的颜色绘制圆圈
                val benchmarkingCirclePaint = Paint().apply {
                    style = Paint.Style.FILL
                    isAntiAlias = true
                    color = paintTempPolylineDefaultColor // 使用对标线的颜色
                }
                canvas.drawCircle(realTimeIndicatorX, benchmarkingY, dp2px(3f), benchmarkingCirclePaint)
            }
        }
    }

    /**
     * 更新线条样式
     */
    private fun updateLineStyle() {
        if (isDashedLineEnabled) {
            // 设置虚线效果：线段长度3dp，间隔3dp
            val dashLength = dp2px(3f)
            val gapLength = dp2px(3f)
            paintSolidLine.pathEffect = DashPathEffect(floatArrayOf(dashLength, gapLength), 0f)
        } else {
            // 设置为实线
            paintSolidLine.pathEffect = null
        }
    }

    /**
     * 根据压力值获取对应的背景颜色
     */
    private fun getBackgroundColorByValue(value: Float): Int {
        return when (value) {
            in 0f..30f -> yAxisStageColors[0]
            in 31f..60f -> yAxisStageColors[1]
            in 61f..80f -> yAxisStageColors[2]
            in 81f..100f -> yAxisStageColors[3]
            else -> yAxisStageColors[0]
        }
    }

    // 公共API方法
    /**
     * 设置压力数据
     * @param stressData 压力数据列表，每个元素代表30分钟的压力值（0-100）
     */
    fun setStressData(stressData: List<CusChartData>) {
        dataValues.clear()
        dataValues.addAll(stressData)
        if (isRealTimeIndicatorEnabled) {
            updateRealTimeIndicator()
        }
        invalidate()
    }

    /**
     * 设置压力数据
     * @param stressData 压力数据列表，每个元素代表30分钟的压力值（0-100）
     */
    fun setStressData(stressData: List<CusChartData>, mData: List<CusChartData>) {
        dataValues.clear()
        dataValues.addAll(stressData)
        if (isRealTimeIndicatorEnabled) {
            updateRealTimeIndicator()
        }
        benchmarkingDataValues.clear()
        benchmarkingDataValues.addAll(mData)
        if (isRealTimeIndicatorEnabled) {
            updateRealTimeIndicator()
        }
        invalidate()
    }

    /**
     * 设置对标压力数据
     * @param stressData 压力数据列表，每个元素代表30分钟的压力值（0-100）
     */
    fun setBenchMarkingData(mData: List<CusChartData>) {
        benchmarkingDataValues.clear()
        benchmarkingDataValues.addAll(mData)
        if (isRealTimeIndicatorEnabled) {
            updateRealTimeIndicator()
        }
        invalidate()
    }

    /**
     * 设置触摸监听器
     */
    fun setOnStressPointTouchListener(listener: OnStressPointTouchListener?) {
        this.touchListener = listener
    }

    /**
     * 获取当前数据
     */
    fun getStressData(): List<CusChartData> {
        return dataValues.toList()
    }

    /**
     * 获取指定时间点的压力值
     * @param timeIndex 时间索引（0-47）
     * @return 压力值（0-100）
     */
    fun getStressValue(timeIndex: Int): Float {
        return if (timeIndex >= 0 && timeIndex < dataValues.size) {
            dataValues[timeIndex].mValue
        } else {
            0f
        }
    }

    /**
     * 设置是否显示折线阴影
     * @param enabled true显示阴影，false不显示阴影
     */
    fun setShadowEnabled(enabled: Boolean) {
        if (isShadowEnabled != enabled) {
            isShadowEnabled = enabled
            invalidate() // 重新绘制
        }
    }

    /**
     * 获取当前阴影显示状态
     * @return true表示显示阴影，false表示不显示阴影
     */
    fun isShadowEnabled(): Boolean {
        return isShadowEnabled
    }

    /**
     * 设置是否启用触摸功能
     * @param enabled true启用触摸，false禁用触摸
     */
    fun setTouchEnabled(enabled: Boolean) {
        if (isTouchEnabled != enabled) {
            isTouchEnabled = enabled
            if (!enabled) {
                // 禁用触摸时，清除当前触摸状态
                isTouching = false
                touchedPointIndex = -1
                invalidate()
            }
        }
    }

    /**
     * 获取当前触摸功能状态
     * @return true表示启用触摸，false表示禁用触摸
     */
    fun isTouchEnabled(): Boolean {
        return isTouchEnabled
    }

    /**
     * 设置线条样式
     * @param isDashed true为虚线，false为实线
     */
    fun setDashedLineEnabled(isDashed: Boolean) {
        if (isDashedLineEnabled != isDashed) {
            isDashedLineEnabled = isDashed
            updateLineStyle()
            invalidate() // 重新绘制
        }
    }

    /**
     * 获取当前线条样式
     * @return true表示虚线，false表示实线
     */
    fun isDashedLineEnabled(): Boolean {
        return isDashedLineEnabled
    }

    /**
     * 设置是否启用实时指示器
     * @param enabled true启用实时指示器，false禁用
     */
    fun setRealTimeIndicatorEnabled(enabled: Boolean) {
        if (isRealTimeIndicatorEnabled != enabled) {
            isRealTimeIndicatorEnabled = enabled
            updateRealTimeIndicator()
            invalidate()
        }
    }

    /**
     * 获取实时指示器状态
     * @return true表示启用，false表示禁用
     */
    fun isRealTimeIndicatorEnabled(): Boolean {
        return isRealTimeIndicatorEnabled
    }

    /**
     * 手动刷新实时指示器位置（可用于定时更新）
     */
    fun refreshRealTimeIndicator() {
        if (isRealTimeIndicatorEnabled) {
            updateRealTimeIndicator()
            invalidate()
        }
    }

    /**
     * 设置选择类型，用于显示柱状背景
     * @param type 选择类型：-1不显示，0(0-30)，1(31-60)，2(61-80)，3(81-100)
     */
    fun setSelectType(type: Int) {
        if (selectType != type) {
            selectType = type
            invalidate()
        }
    }

    /**
     * 获取当前选择类型
     * @return 当前选择类型
     */
    fun getSelectType(): Int {
        return selectType
    }

    /**
     * 设置柱状背景颜色
     * @param color 背景颜色
     */
    fun setColumnBackgroundColor(color: Int) {
        columnBackgroundPaint.color = color
        invalidate()
    }

    /**
     * 设置柱状背景透明度
     * @param alpha 透明度 (0-255)
     */
    fun setColumnBackgroundAlpha(alpha: Int) {
        columnBackgroundPaint.alpha = alpha
        invalidate()
    }

    fun getBeforePointIndex(): Int {
        return beforePointIndex
    }
}